﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace ucFilesOper
{ 
    public partial class TrimLittleFiles : DevExpress.XtraEditors.XtraUserControl
    {
        /// <summary>
        /// 自定义线程执行完毕事件的参数类，记录了是哪一个线程执行完毕
        /// </summary>
        public class DeleteEventArgs : EventArgs
        {
            /// <summary>
            /// 
            /// </summary>
            /// <param name="name">当前删除文件的name</param>
            public DeleteEventArgs(string name)
            {
                _deletedFileName = name;
            }

            private readonly string _deletedFileName;

            /// <summary>
            /// 返回_overThreadName，只读属性
            /// </summary>
            public string DeletedFileName
            {
                get { return _deletedFileName; }
            }
        }

        public delegate void PrintLog(string  msgs);

        private event PrintLog _printLog;

        private void OnPrintLog(string msgs)
        {
            PrintLog handler = _printLog;
            if (handler != null) handler(msgs);
        }

        public delegate void DeleteFileEventHandler(DeleteEventArgs e);

        private event DeleteFileEventHandler _deletdfile;


        /// <summary>
        /// 构造函数中完成功能绑定
        /// </summary>
        private TrimLittleFiles()
        {
            InitializeComponent();
            _printLog += PrintMessageList;
            _deletdfile += DeleteFileIvoke;
        }

       

       
        private  static readonly TrimLittleFiles _oneInstance = new TrimLittleFiles();
        public static TrimLittleFiles OneInstance
        {
            get { return _oneInstance; }
        }
        private string _currentDirPath = "";
        private string []  _filesPath  = null;
        private bool _isIncludeChildDir = false;
        private long MinLengh
        {
            get
            {
                switch (cmbUnit.SelectedItem.ToString())
                {
                    case "KB":
                        return long.Parse(txeMinLengh.Text);
                    case "MB":
                        return long.Parse(txeMinLengh.Text)*1024;
                    case "GB":
                        return long.Parse(txeMinLengh.Text)*1024*1024;
                    default:
                        return long.Parse(txeMinLengh.Text);
                }
            }
        }

        private bool IsIncludedChildren
        {
            get
            {
                switch (cmbIsHaveChildren.SelectedIndex)
                {
                    case 0:
                        return true;
                    case 1:
                        return false;
                    default:
                        return false;
                }
            }
        }

        #region 界面响应

        private void BtnOpenDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog open = new FolderBrowserDialog();
            if (open.ShowDialog() == DialogResult.OK)
            {
                txeDirName.Text = open.SelectedPath;
                _currentDirPath = open.SelectedPath;
               // ShowFiles(txeDirName.Text);
            }
        }

        /// <summary>
        /// 删除碎小文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDoDelete_Click(object sender, EventArgs e)
        {
            lstDeletedFiles.Items.Clear();
            ThreadPool.QueueUserWorkItem((obj) => { DoDeleteInvoke(); });
        }

        #endregion

        #region 私有函数

        private void DeleteFileIvoke(DeleteEventArgs e)
        {
            if (this.lblDeletingFile.InvokeRequired)
            {
               // this.lblDeletingFile.BeginInvoke(_deletdfile, e);
                this.lblDeletingFile.BeginInvoke(_deletdfile, e);
            }
               
            else
            {
                this.lblDeletingFile.Text = e.DeletedFileName;
            }

           
        }

        private int _deleteCount = 0;
        /// <summary>
        /// 由btnDoDelete_Click在线程池中调用
        /// </summary>
        /// <param name="o"></param>
        private void DoDeleteInvoke()
        {
            string[] filesPath = Directory.GetFiles(txeDirName.Text, "*.*",
                                                    IsIncludedChildren
                                                        ? SearchOption.AllDirectories
                                                        : SearchOption.TopDirectoryOnly);
            _deleteCount = 0;
            foreach (string filePath in filesPath)
            {
                FileInfo info = new FileInfo(filePath);
                if (info.Length/1024 < this.MinLengh)
                {
                    PrintMessageList(info.Name);
                    _deletdfile(new DeleteEventArgs(info.Name));
                    _deleteCount++;
                    info.Delete();
                }   
            }
            SomeDelegate del = delegate()
                                   {

                                   };
            del();


        }
        delegate void SomeDelegate();

        private void DeleteIsOverInvoke()
        {


        }

        private  void PrintMessageList ( string  msg )
        {
            if (this.lstDeletedFiles.InvokeRequired)
            {
                this.lstDeletedFiles.BeginInvoke(_printLog, msg);
            }
            else
            {
                lstDeletedFiles.Items.Add(msg);
            }
        }

        private void ShowFiles(string path)
        {
            try
            {
                this._filesPath = Directory.GetFiles(path, @"*.*",
                                                    this._isIncludeChildDir
                                                         ? SearchOption.AllDirectories
                                                         : SearchOption.TopDirectoryOnly);
            }
            catch (Exception)
            {
            }
            lstDeletedFiles.Items.Clear();
            foreach (string str in this._filesPath)
            {
                lstDeletedFiles.Items.Add(str);
            }

        }


      
        #endregion




    }
}
